package io.hellsinger.vortex.ui

import android.view.View
import android.view.View.OnAttachStateChangeListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

fun View.attachJob(
    scope: CoroutineScope,
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> Unit,
) {
    val job = scope.launch(context, start = start, block = block)

    val listener =
        object : OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View) = Unit

            override fun onViewDetachedFromWindow(v: View) {
                job.cancel()
                removeOnAttachStateChangeListener(this)
            }
        }

    job.invokeOnCompletion {
        removeOnAttachStateChangeListener(listener)
    }

    addOnAttachStateChangeListener(listener)
}
